#!/bin/bash

set -e

PROJECT_NAME="mytools-ui"
CONTAINER_NAME="mytools-ui-container"
PORT="5175"
IMAGE_TAG="latest"

echo "🚀 开始部署 MyTools UniApp H5..."

check_docker() {
    if ! command -v docker &> /dev/null; then
        echo "❌ Docker 未安装"
        exit 1
    fi
    echo "✅ Docker 可用"
}

# 检查是否已经构建（更新路径）
check_build() {
    echo "📁 检查构建文件..."
    if [ ! -d "unpackage/dist/build/web" ]; then
        echo "❌ 错误: 未找到构建文件，请先在 HBuilderX 中构建 H5 版本"
        echo "💡 提示: 在 HBuilderX 中点击 '发行' -> '网站-H5手机版'"
        echo "📁 期望路径: unpackage/dist/build/web/"
        exit 1
    fi

    # 显示构建文件信息
    echo "✅ 构建文件检查通过"
    echo "📊 构建文件详情:"
    ls -la unpackage/dist/build/web/
    echo ""
}

build_image() {
    echo "🐳 构建 Docker 镜像: $PROJECT_NAME:$IMAGE_TAG"
    docker build -t $PROJECT_NAME:$IMAGE_TAG .

    if docker images | grep -q "$PROJECT_NAME"; then
        echo "✅ Docker 镜像构建成功"
    else
        echo "❌ Docker 镜像构建失败"
        exit 1
    fi
}

deploy_container() {
    echo "🚢 部署容器..."

    if docker ps -a | grep -q $CONTAINER_NAME; then
        echo "🛑 停止并删除旧容器"
        docker stop $CONTAINER_NAME || true
        docker rm $CONTAINER_NAME || true
        echo "✅ 旧容器已清理"
    fi

    echo "🎯 启动新容器..."
    docker run -d \
        --name $CONTAINER_NAME \
        --network ruoyivue-network \
        -p $PORT:5175 \
        --restart unless-stopped \
        $PROJECT_NAME:$IMAGE_TAG

    echo "✅ 新容器已启动"
}

cleanup() {
    echo "🧹 清理未使用的 Docker 资源..."
    docker image prune -f
    echo "✅ 清理完成"
}

show_info() {
    echo ""
    echo "🎉 ================================="
    echo "🎉     MyTools 部署成功完成!"
    echo "🎉 ================================="
    echo "📱 应用地址: http://localhost:$PORT"
    echo "🐳 容器名称: $CONTAINER_NAME"
    echo "📸 镜像版本: $PROJECT_NAME:$IMAGE_TAG"
    echo "📁 构建路径: unpackage/dist/build/web/"
    echo "⏰ 部署时间: $(date)"
    echo ""

    docker ps --filter "name=$CONTAINER_NAME" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
}

main() {
    echo "🎯 开始自动化部署流程..."
    check_docker
    check_build
    build_image
    deploy_container
    cleanup
    show_info
}

main